package telas;

import inicio.Principal;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileWriter;
import java.util.Scanner;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

@SuppressWarnings("serial")
public class EditarCodigo extends JFrame {
  JTextArea caCodigo;
  File f;


  public EditarCodigo(File f) {
    this.f = f;
    super.setTitle(" ..:: GPUHelp - Ferramenta para Edição de Código ::.. " + f.getName());

    Dimension screenSize = this.getToolkit().getScreenSize();
    int largura = (int) screenSize.getWidth();
    int altura = (int) screenSize.getHeight();

    super.setLayout(null);

    JPanel p = new JPanel();
    p.setLayout(null);
    p.setBounds(0, 0, (int) (largura / 2), (int) (altura * 0.8));

    caCodigo = new JTextArea();
    caCodigo.setBounds(10, 50, (int) (largura / 2) - 80, (int) (altura * 0.8) - 50);
    caCodigo.setEditable(true);

    JScrollPane scroll = new JScrollPane(caCodigo);
    scroll.setBounds(10, 50, (int) (largura / 2), (int) (altura * 0.8));
    p.add(scroll);

    StringBuilder sb = new StringBuilder();

    try {

      Scanner in = new Scanner(f);
      while (in.hasNextLine()) {
        sb.append(in.nextLine()).append("\n");
      }
      in.close();
      caCodigo.setText(sb.toString());

    }

    catch (Exception e) {

      System.out.println(e.getMessage());
    }
    JButton salvar = new JButton("Salvar");
    salvar.setBounds(0, 10, 100, 30);
    salvar.addActionListener(new ActionListener() {

      public void actionPerformed(ActionEvent arg0) {
        salvar();

      }
    });
    p.add(salvar);
    super.add(p);//
    this.setSize((int) (largura / 2) + 30, (int) (altura * 0.85));
    super.setLocation((int) largura / 4, 70);
    super.setVisible(true);

  }


  protected void salvar() {
    try {
      FileWriter fw = new FileWriter(Principal.diretorioUsuario + "/" + Principal.pastaTrabalho + "/" + f.getName());

      String[] temp = caCodigo.getText().split("\\n");
      for (int i = 0; i < temp.length; i++)
        fw.write(temp[i] + "\n");

      fw.flush();
      fw.close();
      dispose();
    }
    catch (Exception de) {
      de.printStackTrace();

    }

  }
}
